--[[
	循环从 gmmqredis 读取命令， 主要是web端写入，也是以后的所有控制命令的入口，采用mq的异步格式
	gmmqredis: 有三个mq(request, response, notify)，都是json编码
	参数： msgsession, msghead， msgbody ,基本参照protobuf的定义来，分成 head，body两块
	msgsession 由命名传入方保证唯一， msgbody里面需要加入md5的签名。debug模式不考虑
	返回： msgsession msghead(msgname, retcode, retstr) , msgbody
]]

local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"

local json = require "cjson.safe"
json.encode_sparse_array(true,1,1)

local redisdao = require "redisdao"
local filelog = require "filelog"
local tabletool = require "tabletool"
local configdao = require "configdao"
local timetool = require "timetool"
local os = os

require "pubenum"

local status, cmd, result, logstr

--表情商品和对应道具的映射表
local goods_to_prop = {
    [1] = 202,  --飞吻
    [2] = 202,  --飞吻
    [3] = 201,  --玫瑰
    [4] = 201,  --玫瑰
	[5] = 206,  --花雨
    [6] = 206,  --花雨
    [20] = 202, --飞吻
}

function docmd(cmd)
    local c = cmd
    skynet.send(".gamedatalog", "lua", "write", "-->" .. cmd)

	cmd = json.decode(cmd)
	if not cmd or type(cmd) ~= "table" then 
        cmd = {msghead = {msgname = c},msgbody = {}}
    end

    local result = nil
    local logstr = nil
    local status = false
    filelog.print("line25", cmd)
	if cmd.msghead.msgname == "charge_diamond" then         --充值钻石
		if cmd.msgbody.comment then
			logstr = string.format("%d,%d,%d,%s", EDiamondChange.CHARGE, cmd.msgbody.rid, cmd.msgbody.value, cmd.msgbody.comment.tradeid)
		else
			logstr = string.format("%d,%d,%d", EDiamondChange.CHARGE, cmd.msgbody.rid, cmd.msgbody.value)
		end
        cmd.msgbody.comment = cmd.msgbody.comment or {}
        cmd.msgbody.comment.charge_type = cmd.msgbody.charge_type or 0
		skynet.send(".gamedatalog", "lua", "write", logstr)
		result = cluster.send("gatenode", ".router", cmd.msghead.msgname, tonumber(cmd.msgbody.rid), tonumber(cmd.msgbody.value), cmd.msgbody.recharge_money, cmd.msgbody.comment)
        if true then
            local fields = nil
            if cmd.msgbody.charge_type == EChargeType.ECHARGE_TYPE_AGENCY then
                fields = {subject="代理后台提现通知邮件", content="在 " .. os.date("%m-%d %H:%M:%S") .. " 代理后台提现转入 "  .. math.floor(cmd.msgbody.value / 100) .. " 金币（本邮件仅做为通知参考，一切以实际转入金币数为准。）"}
			elseif cmd.msgbody.charge_type == EChargeType.ECHARGE_TYPE_AGENCY_PRE then
				fields = {subject="代理后台预提现通知邮件", content="在 " .. os.date("%m-%d %H:%M:%S") .. " 代理后台预提现转入 "  .. math.floor(cmd.msgbody.value / 100) .. " 金币（本邮件仅做为通知参考，一切以实际转入金币数为准。）"}
            else
                fields = {subject="金币购买通知邮件", content="在 " .. os.date("%m-%d %H:%M:%S") .. " 购买 "  .. math.floor(cmd.msgbody.value / 100) .. " 金币（本邮件仅做为通知参考，一切以实际购买金币数为准。）"}
            end
		    result = cluster.send("gatenode", ".router", "newmail", tonumber(cmd.msgbody.rid), fields)
        end
    elseif cmd.msghead.msgname == "charge_prop" then        --充值道具
        local goods_id = tonumber(cmd.msgbody.goods_id) or 0
        local prop_id = goods_to_prop[goods_id] or 0
		if cmd.msgbody.comment then
			logstr = string.format("%d,%d,%d,%d,%s", EGateAction.CHARGEPROP, cmd.msgbody.rid, cmd.msgbody.goods_id, cmd.msgbody.value, cmd.msgbody.comment.tradeid)
		else
			logstr = string.format("%d,%d,%d,%d", EGateAction.CHARGEPROP, cmd.msgbody.rid, cmd.msgbody.goods_id, cmd.msgbody.value)
		end
		skynet.send(".gamedatalog", "lua", "write", logstr)
		result = cluster.send("gatenode", ".router", cmd.msghead.msgname, tonumber(cmd.msgbody.rid), prop_id, cmd.msgbody.value, cmd.msgbody.comment)
	elseif cmd.msghead.msgname == "update_withdraw_state" then  --更新提现状态
		if type(cmd.msgbody.remark) ~= "string" then
			cmd.msgbody.remark = ""
		end
		result = cluster.send("gatenode", ".router", "update_withdraw_state", tonumber(cmd.msgbody.rid), cmd.msgbody.keyid, tonumber(cmd.msgbody.state), cmd.msgbody.remark)
	elseif cmd.msghead.msgname == "givemoney" then  --赠送金币
		local rid = tonumber(cmd.msgbody.rid) or 0
		local tradeid = tostring(cmd.msgbody.tradeid)
		if not tradeid and cmd.msgbody.comment then
			tradeid = tostring(cmd.msgbody.comment.tradeid)
		end
		local fields = {	
			tradeid = tradeid or "",
			sendname = "admin",
			recvname = "xxxxx",
			begin_value = 0,
			end_value = 0,
			recvrid = tonumber(cmd.msgbody.recvrid),
			give_type = tonumber(cmd.msgbody.give_type),
			give_value = tonumber(cmd.msgbody.give_value),
			current_state = EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW,
			remark = tostring(cmd.msgbody.remark),
		}
		cluster.send("gatenode", ".router", "givemoney", rid, fields)
	elseif cmd.msghead.msgname == "cancelgivemoney" then	--撤销赠送
		cluster.send("gatenode", ".router", "cancelgivemoney", cmd.msgbody.keyid, cmd.msgbody.remark, cmd.msgbody.undorid)
	end
	
    --将结果保存到结果队列
    if cmd.id then
        result = result or true
        local response = {id = cmd.id, result = result}
        redisdao.query_data(".gmmqredis", "rpush", "responsemq",json.encode(response))
    elseif cmd.mid then
        local response = {cmd = cmd.msghead.msgname, result = result}
        redisdao.query_data(".gmmqredis", "rpush", "myrespmq",json.encode(response))
    end

    return result
end

skynet.start(function()
	skynet.call(".gmmqredis", "lua", "init", configdao.get_cfgsvrs_key("gmmqredis"))

	-- 就是循环休息1s 去读取一下 gmmqredis 的 request
	-- 如果读到消息了，就不休息，马上再循环
	skynet.fork(function()
		while true do
			local status, cmd = redisdao.query_data(".gmmqredis", "lpop", "inchargemq")
			if status and cmd then
				status,result = pcall(docmd,cmd)
                if not status then
                    filelog.sys_error("docmd error!",cmd)
                end
                filelog.print("line 105", result)
			else
				skynet.sleep(100)
			end
		end
	end)

    --读取inwithdrawmq，处理提现响应消息
    skynet.fork(function()
		while true do
			local status, cmd = redisdao.query_data(".gmmqredis", "lpop", "inwithdrawmq")
			if status and cmd then
				status,result = pcall(docmd,cmd)
                if not status then
                    filelog.sys_error("docmd error!",cmd)
                end
                filelog.print("line 121", result)
			else
				skynet.sleep(100)
			end
		end
	end)
end)
